package com.jorado.etl.service;

import com.jorado.core.Result;
import com.jorado.core.utility.IOUtils;
import com.jorado.event.EventClient;
import com.jorado.fasttext.FilterManager;
import com.jorado.search.core.service.impl.ExportToFileImpl;
import com.jorado.search.core.service.impl.SolrExporter;
import com.jorado.search.core.util.SolrUtils;
import com.jorado.search.solr.client.SolrjOption;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.common.SolrDocument;
import org.springframework.context.annotation.Description;

import java.util.ArrayList;
import java.util.List;

@Description("Solr数据同步到文件")
public final class SolrToFileService extends ExportToFileImpl<SolrDocument> {

    private int total;
    private int waitTime;

    public SolrToFileService(SolrjOption positionSolr, String distFile) {
        this(positionSolr, distFile, true);
    }

    public SolrToFileService(SolrjOption positionSolr, String distFile, boolean deleteIfExists) {
        this(positionSolr, distFile, deleteIfExists, 0);
    }

    public SolrToFileService(SolrjOption positionSolr, String distFile, boolean deleteIfExists, int waitTime) {
        this(positionSolr, getSolrQuery(), distFile, deleteIfExists, waitTime);
    }

    public SolrToFileService(SolrjOption positionSolr, SolrQuery solrQuery, String distFile, boolean deleteIfExists, int waitTime) {
        super(new SolrExporter(positionSolr, solrQuery), distFile, deleteIfExists);
        this.waitTime = waitTime;
        this.setAfterFilter(this::after);
    }

    private static SolrQuery getSolrQuery() {
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setQuery("*:*");
        solrQuery.setFields("JOB_TITLE,JOB_TYPE_NAME,INDUSTRY_NAME,JOB_DESC");
        solrQuery.setSort("DATE_CREATED", SolrQuery.ORDER.asc);
        return solrQuery;
    }

    @Override
    protected void export(List<SolrDocument> dataList) {

        total += dataList.size();

        List<String> lines = new ArrayList<>();

        String jobTitle;
        String jobType;
        String industry;
        String desc;
        for (SolrDocument doc : dataList) {

            jobTitle = SolrUtils.getDocValue(doc, "JOB_TITLE");
            jobType = SolrUtils.getDocValue(doc, "JOB_TYPE_NAME");
            industry = SolrUtils.getDocValue(doc, "INDUSTRY_NAME");
            desc = SolrUtils.getDocValue(doc, "JOB_DESC");
            FilterManager filterManager = new FilterManager();
            desc = filterManager.filter(desc);
            lines.add(String.format("%s……%s……%s……%s", jobTitle, jobType, industry, desc));
        }

        try {
            IOUtils.appendLines(this.distFile, lines);
            Thread.sleep(waitTime);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    protected Result after(Result result) {

        EventClient.getDefault().asyncSubmitLog(String.format("共同步solr职位:[%d]个", total));

        //TODO:对文件去重
        return Result.OK;
    }
}
